package com.sherry.uitils.auth;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

public class RSAEncrypter {
	private static final Logger logger = LogManager.getLogger(RSAEncrypter.class);
	private Cipher ecipher;
	private static ObjectInputStream ois;
	private static PrivateKey privateKey;

	static {
		try {
			ois = new ObjectInputStream(RSAEncrypter.class.getClassLoader().getResourceAsStream("privateKey"));
			privateKey = (PrivateKey) ois.readObject();
		} catch (IOException e) {
			logger.error("", e);
		} catch (ClassNotFoundException e) {
			logger.error("", e);
		} finally {
			try {
				ois.close();
			} catch (IOException e) {
				logger.error("", e);
			}
		}
	}

	public static RSAEncrypter getInstance() {
		return new RSAEncrypter();
	}

	private RSAEncrypter() {
		try {
			this.ecipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			this.ecipher.init(1, privateKey);
		} catch (NoSuchAlgorithmException e) {
			logger.error("", e);
		} catch (NoSuchPaddingException e) {
			logger.error("", e);
		} catch (InvalidKeyException e) {
			logger.error("", e);
		}
	}

	public String encrypt(String source) {
		try {
			byte[] utf8 = source.getBytes("UTF8");
			byte[] enc = this.ecipher.doFinal(utf8);
			return new String(new Base64().encode(enc));
		} catch (IOException e) {
			logger.error("", e);
		} catch (IllegalBlockSizeException e) {
			logger.error("", e);
		} catch (BadPaddingException e) {
			logger.error("", e);
		} catch (Exception e) {
			logger.error("", e);
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(RSAEncrypter.getInstance().encrypt("dagdstgse"));
	}
}
